//
//  WBOAuthViewController.swift
//  Weibo
//
//  Created by yinbo on 2018/3/7.
//  Copyright © 2018年 yinbo. All rights reserved.
//

import UIKit
import SVProgressHUD
//通过webview加载新浪微博授权页面控制器
class WBOAuthViewController: UIViewController {
    lazy var webview = UIWebView()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURL)"
        guard let url = URL(string: urlString) else{
            return
        }
        let request = URLRequest(url: url)
        webview.loadRequest(request)
        
        // Do any additional setup after loading the view.
    }
    override func loadView() {
        view = webview
        view.backgroundColor = UIColor.white
        webview.delegate = self
        webview.scrollView.isScrollEnabled = false
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 16, target:self , action: #selector(autoFill), isBack: false)
    }
    @objc  func close(){
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    //自动填充-webview的注入，直接通过js修改‘本地浏览器中’缓存的页面内容
    @objc private func autoFill(){
    
        let js = "document.getElementById('userId').value = '1522789938@qq.com';" + "document.getElementById('passwd').value = 'clience1992';"
        webview.stringByEvaluatingJavaScript(from: js)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


extension WBOAuthViewController:UIWebViewDelegate{
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print("加载请求---\(request.url?.absoluteString )")
        if request.url?.absoluteString.hasPrefix(WBRedirectURL)  == false {
            return true
        }
        if request.url?.query?.hasPrefix("code=") == false{
            print("取消授权")
            close()
            return false
        }
        
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("获取授权码\(code)")
//        close()
        WBNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess{
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }else{
                SVProgressHUD.showInfo(withStatus: "登陆成功")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessedNotication), object: nil)
                self.close()
            }
        }
        return false
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
